package com.controller;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;

import com.dao.INSERTUserMapper;
import com.entity.Communication;
import com.entity.Count;
import com.entity.Fail;
import com.entity.Unitdoor;
import com.entity.Uploadfile;
import com.entity.Uploadfileto;
import com.entity.Visitors;
import com.entity.countuser;
import com.service.CommunicationService;
import com.service.CountService;
import com.service.FailService;
import com.service.UnitdoorService;
import com.service.UploadService;
import com.service.VisitorsService;

@Controller
@RequestMapping("/updownuserto")
public class updownusertoController {

		@Resource
		INSERTUserMapper iNSERTUserMapper;
		/*
		 * PAD上传人脸接口
		 */
		@ResponseBody
		@RequestMapping(value="/synchronizationuser",produces = "text/html;charset=UTF-8", method=RequestMethod.POST)
		public String synchronizationuser(String Imgbase,String Nuberuser,String Termofvalidity,String idnumberandto,String createtime,String registrationandtype) {
			Map<String, Object> map = new HashMap<String, Object>();
			String msg=null;
			Uploadfileto up = new Uploadfileto();
			Date data=new Date();
	        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss"+"01");
	        String newData = dateFormat.format(data);
	        String str=".jpg";
			String yfilename2="/home/apache-tomcat-7.0.47/webapps/image/upload/"+newData+str;
			String yfilename="https://wwl.ycws.cc/image/upload/"+newData+str;
			String cardnumber=Nuberuser;
			String idnumber=Termofvalidity;
			String ydetailed=null;
			List<Unitdoor>list3 = iNSERTUserMapper.selectPadfin(idnumberandto);
			String yaddress=list3.get(0).getAddress();
			String ydetailedto=list3.get(0).getNumber();
			List<Uploadfileto>list2=iNSERTUserMapper.selectuserone(cardnumber,yaddress);
			
			if(list3.size()==0){//判断PAD是否绑定了
				msg ="400";
				map.put("id", msg);
				new JSONObject();
				JSONObject json=JSONObject.fromObject(map);
				return json.toString();
			}else {
				String miu="all";
				
				if(ydetailedto.equals(miu)){//判断小区在用快速绑定的时候，是有独立的单元楼PAD
					 ydetailed="";
				}else{
					 ydetailed=ydetailedto;
				}
				if(list2.size()==0){//卡号不重复
							BASE64Decoder  deone = new BASE64Decoder();
							try {
								//解密
								byte [] b = deone.decodeBuffer(Imgbase);
								//转换数据
								for (int i=0;i<b.length;++i){
									if(b[i]<0){
										b[i] +=256;
									}
								}
								OutputStream out = new FileOutputStream(yfilename2);
								out.write(b);
								out.flush();
								out.close();
								Date data2=new Date();
				    	        SimpleDateFormat dateFormat2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				    	        String updatetime = dateFormat2.format(data2);
								String yindex="1";
								String examine="1";
								iNSERTUserMapper.insertuser(yfilename, cardnumber, idnumber,yaddress,yindex,createtime,examine,updatetime,registrationandtype,ydetailed);//插入数据
								up = iNSERTUserMapper.selecuser(yfilename);//查询插入的ID
								msg=String.valueOf(up.getYid());
							} catch (FileNotFoundException e) {
								msg="0";
								e.printStackTrace();
							} catch (IOException e) {
								msg="0";
								e.printStackTrace();
							}catch (Exception e) {
								 msg="0";
								e.printStackTrace();
							}
							
							
								
							
							
							map.put("id", msg);
							new JSONObject();
							JSONObject json=JSONObject.fromObject(map);
							return json.toString();
					
				}else {
					
					//卡号重复

					
					BASE64Decoder  deone = new BASE64Decoder();
					try {
						//解密
						byte [] b = deone.decodeBuffer(Imgbase);
						//转换数据
						for (int i=0;i<b.length;++i){
							if(b[i]<0){
								b[i] +=256;
							}
						}
						OutputStream out = new FileOutputStream(yfilename2);
						out.write(b);
						out.flush();
						out.close();
						Date data2=new Date();
		    	        SimpleDateFormat dateFormat2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		    	        String updatetime = dateFormat2.format(data2);
						String yindex="1";
						String examine="1";
						String cardnumberandrepeat="repeat";
						iNSERTUserMapper.insertuserandks(yfilename, cardnumber, idnumber,yaddress,yindex,createtime,examine,updatetime,registrationandtype,cardnumberandrepeat,ydetailed);//插入数据
						up = iNSERTUserMapper.selecuser(yfilename);//查询插入的ID
						msg=String.valueOf(up.getYid());
					} catch (FileNotFoundException e) {
						msg="0";
						e.printStackTrace();
					} catch (IOException e) {
						msg="0";
						e.printStackTrace();
					}catch (Exception e) {
						 msg="0";
						e.printStackTrace();
					}	
					
					
					map.put("id", msg);
					new JSONObject();
					JSONObject json=JSONObject.fromObject(map);
					return json.toString();
			
				}
			}
			
				
		
			
		}
		
		
		
		
		
		/*
		 * ---PAD普通注册上传人脸接口
		 */
		@ResponseBody
		@RequestMapping(value="/CommonandSynchronizationuser",produces = "text/html;charset=UTF-8", method=RequestMethod.POST)
		public String CommonandSynchronizationuser(String Imgbase,String Nuberuser,String Termofvalidity,String idnumberandto,String createtime,String registrationandtype,String yname) {
			Map<String, Object> map = new HashMap<String, Object>();
			String msg=null;
			Uploadfileto up = new Uploadfileto();
			Date data=new Date();
	        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss"+"01");
	        String newData = dateFormat.format(data);
	        String str=".jpg";
			String yfilename2="/home/apache-tomcat-7.0.47/webapps/image/upload/"+newData+str;
			String yfilename="https://wwl.ycws.cc/image/upload/"+newData+str;
			String cardnumber=Nuberuser;
			String idnumber=Termofvalidity;
			List<Unitdoor>list3 = iNSERTUserMapper.selectPadfin(idnumberandto);
			String yaddress=list3.get(0).getAddress();
			String ydetailedyo=list3.get(0).getNumber();
			String ydetailed=null;
			String miu="all";
			if(ydetailedyo.equals(miu)){
				ydetailed="大门";
			}else{
				ydetailed=ydetailedyo;
			}
			
			
			if(list3.size()==0){//判断PAD是否绑定了
				msg ="400";
				map.put("id", msg);
				new JSONObject();
				JSONObject json=JSONObject.fromObject(map);
				return json.toString();
			}else {
				String uf="";
				String ut=null;
				
				if(cardnumber.equals(uf)||cardnumber.equals(ut)){//上传的用户是没有带卡号的
					BASE64Decoder  deone = new BASE64Decoder();
					try {
						//解密
						byte [] b = deone.decodeBuffer(Imgbase);
						//转换数据
						for (int i=0;i<b.length;++i){
							if(b[i]<0){
								b[i] +=256;
							}
						}
						OutputStream out = new FileOutputStream(yfilename2);
						out.write(b);
						out.flush();
						out.close();
						Date data2=new Date();
		    	        SimpleDateFormat dateFormat2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		    	        String updatetime = dateFormat2.format(data2);
						String yindex="1";
						String examine="1";
						iNSERTUserMapper.insertuserandyname(yfilename, cardnumber, idnumber,yaddress,yindex,createtime,examine,updatetime,registrationandtype,yname,ydetailed);//插入数据
						up = iNSERTUserMapper.selecuser(yfilename);//查询插入的ID
						msg=String.valueOf(up.getYid());
					} catch (FileNotFoundException e) {
						msg="0";
						e.printStackTrace();
					} catch (IOException e) {
						msg="0";
						e.printStackTrace();
					}catch (Exception e) {
						 msg="0";
						e.printStackTrace();
					}
					

					
					map.put("id", msg);
					new JSONObject();
					JSONObject json=JSONObject.fromObject(map);
					return json.toString();
					
					}else {//-----------------------用户注册带了卡号	
						List<Uploadfileto>list2=iNSERTUserMapper.selectuserone(cardnumber,yaddress);
						if(list2.size()==0){//---------------------------卡号不重复
									BASE64Decoder  deone = new BASE64Decoder();
									try {
										//解密
										byte [] b = deone.decodeBuffer(Imgbase);
										//转换数据
										for (int i=0;i<b.length;++i){
											if(b[i]<0){
												b[i] +=256;
											}
										}
										OutputStream out = new FileOutputStream(yfilename2);
										out.write(b);
										out.flush();
										out.close();
										Date data2=new Date();
						    	        SimpleDateFormat dateFormat2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						    	        String updatetime = dateFormat2.format(data2);
										String yindex="1";
										String examine="1";
										iNSERTUserMapper.insertuserandyname(yfilename, cardnumber, idnumber,yaddress,yindex,createtime,examine,updatetime,registrationandtype,yname,ydetailed);//插入数据
										up = iNSERTUserMapper.selecuser(yfilename);//查询插入的ID
										msg=String.valueOf(up.getYid());
									} catch (FileNotFoundException e) {
										msg="0";
										e.printStackTrace();
									} catch (IOException e) {
										msg="0";
										e.printStackTrace();
									}catch (Exception e) {
										 msg="0";
										e.printStackTrace();
									}
									
									
										
									
									
									map.put("id", msg);
									new JSONObject();
									JSONObject json=JSONObject.fromObject(map);
									return json.toString();
							
						}else {
							//卡号重复 要给特定的一个标识 repeat 
							BASE64Decoder  deone = new BASE64Decoder();
							try {
								//解密
								byte [] b = deone.decodeBuffer(Imgbase);
								//转换数据
								for (int i=0;i<b.length;++i){
									if(b[i]<0){
										b[i] +=256;
									}
								}
								OutputStream out = new FileOutputStream(yfilename2);
								out.write(b);
								out.flush();
								out.close();
								Date data2=new Date();
				    	        SimpleDateFormat dateFormat2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				    	        String updatetime = dateFormat2.format(data2);
								String yindex="1";
								String examine="1";
								String cardnumberandrepeat="repeat";
								iNSERTUserMapper.insertuserandrepeat(yfilename, cardnumber, idnumber,yaddress,yindex,createtime,examine,updatetime,registrationandtype,cardnumberandrepeat,yname,ydetailed);//插入数据
								up = iNSERTUserMapper.selecuser(yfilename);//查询插入的ID
								msg=String.valueOf(up.getYid());
							} catch (FileNotFoundException e) {
								msg="0";
								e.printStackTrace();
							} catch (IOException e) {
								msg="0";
								e.printStackTrace();
							}catch (Exception e) {
								 msg="0";
								e.printStackTrace();
							}
							
		
							
							map.put("id", msg);
							new JSONObject();
							JSONObject json=JSONObject.fromObject(map);
							return json.toString();
							
						}
						
						
					}
				
				
				
			}
					
		}
		
		
		
		
		/*
		 * ---PAD刷卡抓拍人脸上传
		 */
		@ResponseBody
		@RequestMapping(value="/CommonandSynchronizationusertosnapshotrecord",produces = "text/html;charset=UTF-8", method=RequestMethod.POST)
		public String CommonandSynchronizationusertosnapshotrecord(String Imgbase,String Nuberuser,String createtime,String idnumberandto) {
			Map<String, Object> map = new HashMap<String, Object>();
			String msg=null;
			Date data=new Date();
	        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss"+"01");
	        String newData = dateFormat.format(data);
	        String str=".jpg";
			String yfilename2="/home/apache-tomcat-7.0.47/webapps/image/zp/"+newData+str;
			String yfilename="https://wwl.ycws.cc/image/zp/"+newData+str;
	       /* String yfilename2="D:/"+newData+str;
	        String yfilename="D:/"+newData+str;*/
			String cardnumber=Nuberuser;//卡号
			List<Unitdoor>list3 = iNSERTUserMapper.selectPadfin(idnumberandto);//根据PAD序列号查询有没有绑定
			String yaddress=list3.get(0).getAddress();
			String ydetailedto=list3.get(0).getNumber();
			String ydetailed=null;
			
			if(list3.size()==0){//判断PAD是否绑定了
				msg ="400";
				map.put("id", msg);
				new JSONObject();
				JSONObject json=JSONObject.fromObject(map);
				return json.toString();
			}else {
					BASE64Decoder  deone = new BASE64Decoder();
					try {
						//解密
						byte [] b = deone.decodeBuffer(Imgbase);
						//转换数据
						for (int i=0;i<b.length;++i){
							if(b[i]<0){
								b[i] +=256;
							}
						}
						OutputStream out = new FileOutputStream(yfilename2);
						out.write(b);
						out.flush();
						out.close();
						if(ydetailedto.equals("all")){
							ydetailed="大门";
						}else {
							ydetailed=ydetailedto;
						}
						iNSERTUserMapper.insertuserandsnapshotrecord(yfilename, cardnumber, yaddress, createtime, ydetailed);
						msg="1";
					} catch (FileNotFoundException e) {
						msg="0";
						e.printStackTrace();
					} catch (IOException e) {
						msg="0";
						e.printStackTrace();
					}catch (Exception e) {
						 msg="0";
						e.printStackTrace();
					}					
					
					map.put("id", msg);
					new JSONObject();
					JSONObject json=JSONObject.fromObject(map);
					return json.toString();
		
			}
					
		}
		
		
		
		@ResponseBody
		@RequestMapping(value="/selecetusercount",produces = "text/html;charset=UTF-8", method=RequestMethod.POST)
		public String selecetusercount(String statretime,String enttime) {
			Map<String , Object>map = new HashMap<String, Object>();
			List<countuser> listone;
			try {
				listone = iNSERTUserMapper.selectusercont(statretime,enttime);
				map.put("list", listone);
			} catch (Exception e) {
				map.put("0000", "数据查询错误");
				e.printStackTrace();
			}
			
			new JSONObject();
			JSONObject json=JSONObject.fromObject(map);
			return json.toString();
		}
		
		
		
		@ResponseBody
		@RequestMapping(value="/synchronizationuser2",produces = "text/html;charset=UTF-8", method=RequestMethod.GET)
		public String synchronizationuser() {
			String imgFile = "C:/0/2017102715121801.jpg";//待处理的图片  
	        InputStream in = null;  
	        byte[] data = null;  
	        //读取图片字节数组  
	        try   
	        {  
	            in = new FileInputStream(imgFile);          
	            data = new byte[in.available()];  
	            in.read(data);  
	            in.close();  
	        }   
	        catch (IOException e)   
	        {  
	            e.printStackTrace();  
	        }  
	        //对字节数组Base64编码  
	        BASE64Encoder encoder = new BASE64Encoder();  
	       // return encoder.encode(data);//返回Base64编码过的字节数组字符串 
	        String Imgbase=encoder.encode(data);
	        String Nuberuser="123456";
	        String Termofvalidity="20171123";
	        //String aa=doPostSelect(Imgbase, Nuberuser, Termofvalidity);
	       // String a= ssss(Imgbase, Nuberuser, Termofvalidity);
	        String filePath="C:\\shuchu\\yang.txt";
	        String content=encoder.encode(data);
	        //String content="杨志威";
	        contentToTxt( filePath,content);
			return null;
		}
		
/*		public String ssss(String Imgbase,String Nuberuser,String Termofvalidity){
			Map<String, Object> map = new HashMap<String, Object>();
			String msg=null;
			Uploadfileto up = new Uploadfileto();
			Date data=new Date();
	        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss"+"01");
	        String newData = dateFormat.format(data);
	        String str=".jpg";
			String yfilename="C:/0/"+newData+str;
			String cardnumber=Nuberuser;
			String idnumber=Termofvalidity;
			if(Imgbase==null){
				msg ="0";
				map.put("state", msg);
				new JSONObject();
				JSONObject json=JSONObject.fromObject(map);
				return json.toString();
			}else {
					BASE64Decoder  deone = new BASE64Decoder();
					try {
						//解密
						byte [] b = deone.decodeBuffer(Imgbase);
						//转换数据
						for (int i=0;i<b.length;++i){
							if(b[i]<0){
								b[i] +=256;
							}
						}
						OutputStream out = new FileOutputStream(yfilename);
						out.write(b);
						out.flush();
						out.close();
						
						iNSERTUserMapper.insertuser(yfilename, cardnumber, idnumber);//插入数据
						up = iNSERTUserMapper.selecuser(yfilename);//查询插入的ID
						
					} catch (FileNotFoundException e) {
						msg="0";
						e.printStackTrace();
					} catch (IOException e) {
						msg="0";
						e.printStackTrace();
					}catch (Exception e) {
						 msg="0";
						e.printStackTrace();
					}
					
		
					msg=String.valueOf(up.getYid());
					map.put("id", msg);
					new JSONObject();
					JSONObject json=JSONObject.fromObject(map);
					return json.toString();
			}
			
		}*/
		
		
	    public static String doPostSelect(String Imgbase,String Nuberuser,String Termofvalidity) {
	    	String urlStr="https://wwl.ycws.cc/ssm/updownuserto/synchronizationuser";
	        String result = null;
	        HttpPost httpPost = new HttpPost(urlStr);
	    	List<NameValuePair> params = new ArrayList<NameValuePair>();
	    	params.add(new BasicNameValuePair("Imgbase",Imgbase));
	    	params.add(new BasicNameValuePair("Nuberuser",Nuberuser));
	    	params.add(new BasicNameValuePair("Termofvalidity",Termofvalidity));
	        try {

	        	HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");// 设置字符集
	            httpPost.setEntity(entity);// 设置参数实体
	            @SuppressWarnings("resource") 
	            HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
	            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
	            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时
	            HttpResponse httpResp = httpClient.execute(httpPost);// 获取HttpResponse实例
	            if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
	                result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
	            } else {
	                result="100";
	            }
	        } catch (ConnectTimeoutException e) {
	        	result="100";
	        } catch (UnsupportedEncodingException e) {
	        	result="100";
	        } catch (IOException e) {
	        	result="100";
	        } catch (Exception e) {
	        	result="100";
	        }

	        return result;
	    }
	    
	    public static void contentToTxt(String filePath, String content) {  
	        try {
	        	 String str = new String(); //原有txt内容  
	             String s1 = new String();//内容更新  
	             try {  
	                 File f = new File(filePath);  
	                 /*if (f.exists()) {  
	                     System.out.print("文件存在");  
	                 } else {  
	                     System.out.print("文件不存在");  
	                     f.createNewFile();// 不存在则创建  
	                 } */ 
	                 BufferedReader input = new BufferedReader(new FileReader(f));  
	       
	                 while ((str = input.readLine()) != null) {  
	                     s1 += str + "\n";  
	                 }  
	                 //System.out.println(s1);  
	                 input.close();  
	                 s1 += content;  
	       
	                 BufferedWriter output = new BufferedWriter(new FileWriter(f));  
	                 output.write(s1);  
	                 output.close();  
	             } catch (Exception e) {  
	                 e.printStackTrace();  
	       
	             }  
	         
	        	/* 写入Txt文件   
                File writename = new File(filePath); // 相对路径，如果没有则要建立一个新的output。txt文件  
                writename.createNewFile(); // 创建新文件  
                BufferedWriter out = new BufferedWriter(new FileWriter(writename));//true,则追加写入text文本 
                //BufferedWriter out = new BufferedWriter(new FileWriter(writename));  
                out.write(content); // \r\n即为换行  
                out.flush(); // 把缓存区内容压入文件  
                out.close(); // 最后记得关闭文件   
*/	        } catch (Exception e) {  
	            e.printStackTrace();  
	  
	        }  
	    } 
	    
	    /** 
	     * 创建文件 
	     * @param fileName 
	     * @return 
	     */  
	    public static boolean createFile(File fileName)throws Exception{  
	     boolean flag=false;  
	     try{  
	      if(!fileName.exists()){  
	       fileName.createNewFile();  
	       flag=true;  
	      }  
	     }catch(Exception e){  
	      e.printStackTrace();  
	     }  
	     return true;  
	    } 
		
		
	}
